from flask import Flask,request,jsonify,make_response
from flask_cors import CORS
from user.reg import bp_user
from db import db
from flask import Blueprint
from config import Config
import time
import json
#实例对象
app = Flask(__name__)
#中文乱码
# app.config['JSON_AS_ASCII'] = False
app.config.from_object(Config)

app.register_blueprint(bp_user,url_prefix='/user')
cors = CORS(app)




@app.before_first_request
def before():
    #获取新闻
    url = request.url
    #生成开始时间
    stime = time.time()
    #添加数据库
    sql = '''insert into news(url,stime) values('%s','%s')''' %(url,stime)
    db.insert(sql)
    # return jsonify({'code':200})

@app.after_request
def alter(response):
     #获取新闻
    url = request.url
    #生成开始时间
    etime = time.time()
    sql = "select * from news where url='%s' and etime is null "%(url)
    res = db.findone(sql)

    sql = '''update news set etime = '%s' where id = %d and etime is null '''%(etime,int(res['id']))
    db.update(sql)
    return make_response(response)

@app.route('/',methods=['POST','GET'])
def add():
    if request.method == 'POST':
        data = json.loads(request.data)

        sql = '''insert into news2(title) values('%s')''' %(data['title'])
        db.insert(sql)
        return ({'code':200})

       
if __name__ == '__main__':
    app.run(debug=True,port=5000,host='0.0.0.0')